package com.itheima.service.impl;

import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * The type Dept service.
 */
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Dept> list() {
        return deptMapper.selectList();
    }

    @Override
    public void deleteById(Integer id) {
        // 如果部门下还有人就不能删除
//        Integer count = empMapper.selectCountByDeptId(id);
//        if (count != 0) {
//            throw new RuntimeException("部门还有人");
//        }
        deptMapper.deleteById(id);
    }

    @Override
    public void save(Dept dept) {
        String name = dept.getName();
        if (Objects.isNull(name)) {
            throw new RuntimeException("名字不能为空");
        }
        if (name.length() < 2 || name.length() > 10) {
            throw new RuntimeException("名字长度不合法");
        }
        Integer countByName = deptMapper.selectCountByName(name);
        if (countByName > 0) {
            throw new RuntimeException("部门已经存在");
        }
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.save(dept);
    }

    @Override
    public Dept selectDeptById(Integer id) {
        return deptMapper.selectDeptById(id);
    }

    @Override
    public void updateDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        // 进行部门名称校验
        Integer count = deptMapper.selectDeptExists(dept.getName());
        if (count != 0) {
            throw new RuntimeException("部门已经存在,请重新输入");
        }
        deptMapper.updateDept(dept);
    }
}
